﻿using System;
using System.Collections;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.Conditional
{
	/// <summary>
	/// 类型判断的Handler
	/// </summary>
	public class IsTypeHandler : CompareHandler
	{
		private const string NULL_VALUE = "Null";
		private const string LIST_VALUE = "List";
		private const string INTEGER_VALUE = "Integer";
		private const string NUMBER_VALUE = "Number";
		private const string String_VALUE = "String";
		private const string BOOLEAN_VALUE = "Boolean";
		private const string DATETIME_VALUE = "DateTime";
		private const string OBJECT_VALUE = "Object";

		protected override bool DoCompareValue ( object propertyValue, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var compareValue = this.Element.CompareValue;
			if ( propertyValue == null )
			{
				return ( compareValue == IsTypeHandler.NULL_VALUE );
			}
			if ( propertyValue is IList )
			{
				return ( compareValue == IsTypeHandler.LIST_VALUE );
			}
			if ( propertyValue is IDictionary )
			{
				return ( compareValue == IsTypeHandler.OBJECT_VALUE );
			}
			var typeCode = Type.GetTypeCode ( propertyValue.GetType ( ) );
			var typeName = IsTypeHandler.NULL_VALUE;
			switch ( typeCode )
			{
				case TypeCode.DBNull:
				case TypeCode.Empty:
					typeName = IsTypeHandler.NULL_VALUE;
					break;

				case TypeCode.Int16:
				case TypeCode.Int32:
				case TypeCode.Int64:
					typeName = IsTypeHandler.INTEGER_VALUE;
					break;

				case TypeCode.Double:
				case TypeCode.Decimal:
				case TypeCode.Single:
					typeName = IsTypeHandler.NUMBER_VALUE;
					break;

				case TypeCode.Char:
				case TypeCode.String:
					typeName = IsTypeHandler.String_VALUE;
					break;

				case TypeCode.DateTime:
					typeName = IsTypeHandler.DATETIME_VALUE;
					break;
			}
			return ( typeName == compareValue );
		}
	}
}
